//
//  EditInverterInfoView.swift
//  ezyform
//
//  Created by Moennig Q on 13/9/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
class EditInverterInfoView: GreenNaviBarView {
    lazy var disposeBag = DisposeBag()
    let tableView = EditInverterTableView()
    var saveBtn = OperationButton(R.string.localizable.save(),enabled: true)
    lazy var addBtn: UIButton = {
        let view = UIButton()
        view.setImage(UIImage(named: "PVDDetail_systeminfo_add"), for: .normal)
        return view
    }()
    override func setUpView(){
        //MARK: - addbtn
        self.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.right.equalTo(-8)
            make.height.width.equalTo(40)
            make.centerY.equalTo(backToPreBtn)
        }
        let contentBackView = UIView()
        contentBackView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        self.addSubview(contentBackView)
        contentBackView.snp.makeConstraints { make in
            make.top.equalTo(topBackView.snp.bottom).offset(-20)
            make.left.right.bottom.equalToSuperview()
        }
        //
        contentBackView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.left.equalTo(Constant.AllOutMargin)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.greaterThanOrEqualTo(0)
        }
        contentBackView.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(OperationButton.bottomMargin)
            make.left.right.equalTo(tableView)
            make.height.equalTo(48)
            make.top.equalTo(tableView.snp.bottom).offset(Constant.AllOutMargin)
        }
    }
    func setData(_ list: [InstallationDetailSystemDetailForInverterModel]){
        self.tableView.loadData(list)
        self.checkEverythingValid()
    }
    //MARK: - 必填项数据绑定控制saveBtn 是否可用
    private func checkEverythingValid(){
        let everythingValid = self.tableView.rx.observe(Array<InstallationDetailSystemDetailForInverterModel>.self, "list").map({ list in
            var validFlag: Bool = true
            if let list = list {
                list.forEach { inverterModel in
                    if inverterModel.inverter_model == "" || inverterModel.number_inverters == 0{
                        validFlag = false
                    }
                }
            }
            return validFlag
        }).share(replay: 1)
        
        //
        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.saveBtn.enableBtn()
            }else{
                strongSelf.saveBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
}
